from flask import Flask, request, jsonify
from flask_cors import CORS
from models import db, Department
from config import Config
from datetime import datetime
import logging

app = Flask(__name__)
app.config.from_object(Config)
CORS(app, resources={r"/api/*": {"origins": "*"}})

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('department_api')

# 初始化数据库
db.init_app(app)

# 统一错误处理
@app.errorhandler(404)
def not_found(error):
    return jsonify({
        'code': 404,
        'msg': '资源未找到',
        'data': None
    }), 404


@app.errorhandler(400)
def bad_request(error):
    return jsonify({
        'code': 400,
        'msg': '请求参数错误',
        'data': None
    }), 400


@app.errorhandler(500)
def internal_error(error):
    return jsonify({
        'code': 500,
        'msg': '服务器内部错误',
        'data': None
    }), 500

    # 健康检查端点
@app.route('/')
def index():
    return jsonify({
        'code': 200,
        'msg': 'API 服务运行中',
        'data': {
            'service': '部门管理系统 API',
            'status': 'running',
            'version': '1.0.0'
        }
    })

    # 部门管理 RESTful API
@app.route('/api/departments', methods=['GET'])
def get_departments():
    logger.info("收到获取部门列表请求")
    try:
        departments = Department.query.all()
        logger.info(f"成功获取 {len(departments)} 个部门")

        # 使用列表推导式确保所有记录都有有效的时间字符串
        departments_data = [dept.to_dict() for dept in departments]

        return jsonify({
            'code': 200,
            'msg': '成功获取部门列表',
            'data': departments_data
        })
    except Exception as e:
        logger.error(f'获取部门列表失败: {str(e)}')
        return jsonify({
            'code': 500,
            'msg': '获取部门列表失败',
            'data': None
        }), 500


@app.route('/api/departments/<int:id>', methods=['GET'])
def get_department(id):
    try:
        department = Department.query.get(id)
        if not department:
            return jsonify({
                'code': 404,
                'msg': f'部门ID {id} 不存在',
                'data': None
            }), 404

        return jsonify({
            'code': 200,
            'msg': '成功获取部门信息',
            'data': department.to_dict()
        })
    except Exception as e:
        logger.error(f'获取部门信息失败: {str(e)}')
        return jsonify({
            'code': 500,
            'msg': '获取部门信息失败',
            'data': None
        }), 500

        @app.route('/api/departments', methods=['POST'])
def create_department():
    try:
        data = request.get_json()
        if not data or 'name' not in data:
            return jsonify({
                'code': 400,
                'msg': '缺少部门名称参数',
                'data': None
            }), 400

        name = data['name'].strip()
        if not name:
            return jsonify({
                'code': 400,
                'msg': '部门名称不能为空',
                'data': None
            }), 400

        # 检查部门是否已存在
        if Department.query.filter_by(name=name).first():
            return jsonify({
                'code': 400,
                'msg': f'部门名称 "{name}" 已存在',
                'data': None
            }), 400

        department = Department(name=name)
        db.session.add(department)
        db.session.commit()

        return jsonify({
            'code': 200,
            'msg': '部门创建成功',
            'data': department.to_dict()
        })
    except Exception as e:
        db.session.rollback()
        logger.error(f'创建部门失败: {str(e)}')
        return jsonify({
            'code': 500,
            'msg': f'创建部门失败: {str(e)}',
            'data': None
        }), 500


@app.route('/api/departments/<int:id>', methods=['PUT'])
def update_department(id):
    try:
        department = Department.query.get(id)
        if not department:
            return jsonify({
                'code': 404,
                'msg': f'部门ID {id} 不存在',
                'data': None
            }), 404

        data = request.get_json()
        if not data or 'name' not in data:
            return jsonify({
                'code': 400,
                'msg': '缺少部门名称参数',
                'data': None
            }), 400

        name = data['name'].strip()
        if not name:
            return jsonify({
                'code': 400,
                'msg': '部门名称不能为空',
                'data': None
            }), 400

        # 检查新名称是否与其他部门冲突
        existing_dept = Department.query.filter(
            Department.name == name,
            Department.id != id
        ).first()

        if existing_dept:
            return jsonify({
                'code': 400,
                'msg': f'部门名称 "{name}" 已被使用',
                'data': None
            }), 400

        department.name = name
        db.session.commit()

        return jsonify({
            'code': 200,
            'msg': '部门更新成功',
            'data': department.to_dict()
        })
    except Exception as e:
        db.session.rollback()
        logger.error(f'更新部门失败: {str(e)}')
        return jsonify({
            'code': 500,
            'msg': '更新部门失败',
            'data': None
        }), 500

        @app.route('/api/departments/<int:id>', methods=['DELETE'])
def delete_department(id):
    try:
        department = Department.query.get(id)
        if not department:
            return jsonify({
                'code': 404,
                'msg': f'部门ID {id} 不存在',
                'data': None
            }), 404

        db.session.delete(department)
        db.session.commit()

        return jsonify({
            'code': 200,
            'msg': '部门删除成功',
            'data': None
        })
    except Exception as e:
        db.session.rollback()
        logger.error(f'删除部门失败: {str(e)}')
        return jsonify({
            'code': 500,
            'msg': '删除部门失败',
            'data': None
        }), 500


if __name__ == '__main__':
    # 创建数据库表（如果不存在）
    with app.app_context():
        try:
            db.create_all()
            logger.info("数据库表创建/验证成功")
        except Exception as e:
            logger.error(f"数据库初始化失败: {str(e)}")

    app.run(debug=True, port=5000)